/**
 * Created by ptt on 2016/5/27/0027.
 */
define(["./dataHandle.js", "./tpl.js", "../maintools/Controller.js", "../popup/listener.js"], function (handle, tpl, Controller) {
    //initial searchbox has bug for global value jQuery
    Controller = Controller.Controller;
    tpl = tpl.slicepage;
    var presentPage = 0;
    var data = handle.statistical;
    var mainElem = $("#popup .js-popup");
    mainElem.html(tpl.render(data));

    var toggleClass = Controller.create({
        elements: {
            ".js-pre": "preButton",
            ".js-next": "nextButton",
            ".pageindex": "pageInde",
            ".css-slicepage": 'mainPage',
            'dt': 'dt',
            'dd': 'dd'
            //".js-confirm": "confirmButton"
        },
        events: {
            "click .js-pre": "prePage",
            "click .js-next": "nextPage",
            "click .pageindex": "selectPage",
            'click .css-slicepage': 'showPage',
            "click dt": "changecontent"
            //"click .js-confirm": "loadLayer",
            //"mousedown .js-confirm": "setStyle",
            //"mouseup": "restoreStyle"
        },
        template: "#tslicepage",
        changecontent: function (e) {
            e.stopPropagation();
            this.dt.removeClass('selected');
            $(e.currentTarget).addClass('selected');
            this.dd.removeClass('selected');
            $(e.currentTarget).next().addClass('selected');
            this.subTrigger[$(e.currentTarget).next().data('content')].button.click();
            if (e.currentTarget.offsetLeft > 104)  {
                $(e.currentTarget).parent().css('left', 100 - e.currentTarget.offsetLeft);
                $(e.currentTarget).next().css('left', e.currentTarget.offsetLeft - 96);
            } else {
                $(e.currentTarget).parent().css('left', '');
            }
        },
        showPage: function (e) {
            var index = $(e.currentTarget).data('index');
            var pageData = data[index];
            this.mainPage.find('p').css('background-color', "");
            this.mainPage.stop().animate({
                height: '35px'
            });
            $(e.currentTarget).find('p').eq(0).css('background-color', "#72bb00");
            $(e.currentTarget).stop().animate({
                height: '300px'
            });
            this.mouseScroll($(".scrolling"));
            e.stopPropagation();
            if ( !$(e.currentTarget).data('has')) {
                var ddlist = $(e.currentTarget).find("dd");
                this.createAllTrigger(ddlist, pageData);
                $(e.currentTarget).data('has', true);
            }
            $(e.currentTarget).find('dt').eq(0).click();
        },
        jrt: function() {
            this.preButton.hover(this.proxy(function (e) {
                this.promptin("pre_prompt", "上一页");
            }), this.proxy(function (e) {
                this.promptout("pre_prompt");
            }));
            this.nextButton.hover(this.proxy(function (e) {
                this.promptin("next_prompt", "下一页");
            }), this.proxy(function (e) {
                this.promptout("next_prompt");
            }));
            this.pageInde.hover(this.proxy(function (e) {
                var text = handle.statistical[$(e.target).text() - 1].title;
                this.promptin("pageindex_prompt", text);
            }), this.proxy(function (e) {
                this.promptout("pageindex_prompt");
            }));
        },
        promptin: function (klass, text) {
            var prompt = $("#prompt");
            prompt.find("p.text").text(text);
            prompt.addClass(klass);
        },
        promptout: function (klass) {
            $("#prompt").removeClass(klass);
        },
        prePage: function () {
            var dl = this.el.find(".css-slicepage dl");
            dl.css("overflow", "hidden");
            dl.animate({
                "left": "100%"
            }, this.proxy(function () {
                presentPage = presentPage - 1;
                presentPage = presentPage < 0 ? 0 : presentPage;
                data = handle.statistical[presentPage];
                this.render(data);
                this.mouseScroll($(".scrolling"));
                var ddlist = this.el.find(".css-slicepage dl dd");
                this.createAllTrigger(ddlist);
                var dl = this.el.find(".css-slicepage dl");
                dl.css({
                    left: "-100%",
                    overflow: "hidden"
                });
                dl.animate({
                    "left": "0"
                }, function () {
                    dl.css("overflow", "");
                });
                this.proxy(this.jrt)();
            }));
        },
        nextPage: function () {
            var dl = this.el.find(".css-slicepage dl");
            dl.css("overflow", "hidden");
            dl.animate({
                "left": "-100%"
            }, this.proxy(function () {
                presentPage = (presentPage + 1) % handle.statistical.length;
                data = handle.statistical[presentPage];
                this.render(data);
                this.mouseScroll($(".scrolling"));
                var ddlist = this.el.find(".css-slicepage dl dd");
                this.createAllTrigger(ddlist);
                var dl = this.el.find(".css-slicepage dl");
                dl.css({
                    left: "100%",
                    overflow: "hidden"
                });
                dl.animate({
                    "left": "0"
                }, function () {
                    dl.css("overflow", "");
                });
                this.proxy(this.jrt)();
            }));
        },
        selectPage: function (e) {
            if (presentPage === $(e.target).text() - 1) return;
            var left = $(e.target).text() - 1 > presentPage;
            var dl;
            if (left) {
                presentPage = $(e.target).text() - 1;
                dl = this.el.find(".css-slicepage dl");
                dl.css("overflow", "hidden");
                dl.animate({
                    "left": "-100%"
                }, this.proxy(function () {
                    data = handle.statistical[presentPage];
                    this.render(data);
                    this.mouseScroll($(".scrolling"));
                    var ddlist = this.el.find(".css-slicepage dl dd");
                    this.createAllTrigger(ddlist);
                    var dl = this.el.find(".css-slicepage dl");
                    dl.css({
                        left: "100%",
                        overflow: "hidden"
                    });
                    dl.animate({
                        "left": "0"
                    }, function () {
                        dl.css("overflow", "");
                    });
                    this.proxy(this.jrt)();
                }));
            } else {
                presentPage = $(e.target).text() - 1;
                dl = this.el.find(".css-slicepage dl");
                dl.css("overflow", "hidden");
                dl.animate({
                    "left": "100%"
                }, this.proxy(function () {
                    data = handle.statistical[presentPage];
                    this.render(data);
                    this.mouseScroll($(".scrolling"));
                    var ddlist = this.el.find(".css-slicepage dl dd");
                    this.createAllTrigger(ddlist);
                    var dl = this.el.find(".css-slicepage dl");
                    dl.css({
                        left: "-100%",
                        overflow: "hidden"
                    });
                    dl.animate({
                        "left": "0"
                    }, function () {
                        dl.css("overflow", "");
                    });
                    this.proxy(this.jrt)();
                }));
            }
        },
        subTrigger: [],
        createTrigger: function (selector, model, parentModel) {
            model = model || {};
            var trigger = Controller.create({
                elements: {
                    ".js_years": "selectYear",
                    ".js_date": "selectDate",
                    ".js_kpi": "selectKpi",
                    ".js_charts": "selectChart",
                    ".js_selector": "querySelect",
                    "button": "button"
                },
                events: {
                    "click button": "toggleLayer",
                    "change select": "changeLayer",
                    "mousedown button": "setStyle",
                    "mouseup": "restoreStyle",
                    "input input": "changeLayer",
                    'click span': 'changeLayer'
                },
                init: function (element) {
                    this.el = jQuery(element);
                    this.refreshElements();
                    this.delegateEvents();
                    Message_bone.on("removeLayer", this.proxy(function () {
                        var renderData = {
                            buttonStat: this.model.buttonStat,
                            condition: this.model.condition,
                            value: this.model.input
                        };
                        this.render(renderData);
                    }));
                },
                destroy: function () {
                    Message_bone.off("removeLayer");

                },
                template: "#tdd",

                toggleLayer: function (e) {
                    e.stopPropagation();
                    if (this.button.hasClass("js-loading")) return;
                    this.model.canTrigger = true;
                    this.model.triggered = true;
                    for (var name in this.parentModel) {
                        var otherModel = this.parentModel[name];
                        if (this.parentModel.hasOwnProperty(name) && this.model !== otherModel) {
                            otherModel.event && otherModel.event.trigger("removeLayer", otherModel);
                            otherModel.triggered = false;
                            Message_bone.trigger("closeButtonHide");
                        }
                    }
                    if (this.button.hasClass("js-confirm")) {
                        Message_bone.one("loading", this.proxy(function () {
                            var renderData = {
                                buttonStat: this.model.buttonStat,
                                condition: this.model.condition,
                                value: this.model.input
                            };
                            this.render(renderData);
                        }));

                        Message_bone.one("loaded", this.proxy(function () {
                            var renderData = {
                                buttonStat: this.model.buttonStat,
                                condition: this.model.condition,
                                value: this.model.input
                            };
                            this.render(renderData);
                        }));
                        var data = {
                            url: this.el.attr("data-baseUrl"),
                            query: this.el.attr("data-query"),
                            queryName: this.el.attr("data-queryname"),
                            layer: this.el.attr("data-layer"),
                            symbol: this.el.attr("data-symbol"),
                            detail: this.el.attr("data-detail"),
                            content: this.el.attr("data-content"),
                            value: this.model.getValue()
                        };
                        this.model.event.trigger("loadLayer", data);
                    } else {
                        this.model.event.trigger("removeLayer", this.model);
                        this.model.triggered = false;
                        Message_bone.trigger("closeButtonHide");
                    }
                },
                setStyle: function () {
                    if (this.button.hasClass("js-loading")) return;
                    this.button.css({
                        "box-shadow": "0 0 8px 4px rgb(229, 229, 229) inset"
                    })
                },
                restoreStyle: function () {
                    if (this.button.hasClass("js-loading")) return;
                    this.button.css({
                        "box-shadow": ""
                    })
                },

                changeLayer: function (e) {
                    if (e.currentTarget.nodeName.toLowerCase() === 'span') {
                        var type = $(e.currentTarget).data('type');
                        var selector = 'span.' + type;
                        $(selector).removeClass('selected');
                        $(e.currentTarget).addClass('selected');
                    }
                    var value = {
                        "years": this.el.find(".js_years").prop("value")
                            || this.el.find("span.years.selected").text(),
                        "sYears": this.el.find(".js_sYears").prop("value"),
                        "sMonth": this.el.find(".js_sMonth").prop("value"),
                        "sDay": this.el.find(".js_sDay").prop("value"),
                        "eYears": this.el.find(".js_eYears").prop("value"),
                        "eMonth": this.el.find(".js_eMonth").prop("value"),
                        "eDay": this.el.find(".js_eDay").prop("value"),
                        "kpi": this.el.find(".js_kpi").prop("value")
                            || this.el.find("span.kpi.selected").text(),
                        "charts": this.el.find(".js_charts").prop("value")
                            || this.el.find("span.charts.selected").text(),
                        "selector": this.el.find(".js_selector").prop("value")
                            || this.el.find("span.selector.selected").text(),
                        "type": this.el.find(".js_type").prop("value")
                            || this.el.find("span.type.selected").text(),
                        "fromParam": this.el.find(".js_fromParam").prop("value")
                            || this.el.find("span.fromParam.selected").text()
                    };
                    this.model.input = value;
                    var renderData = {
                        buttonStat: this.model.buttonStat,
                        condition: this.model.condition,
                        value: this.model.input
                    };
                    this.render(renderData);
                    if (!this.model.layer || !this.model.triggered) return;
                    if (e.target.nodeName.toLowerCase() === "input") {
                        this.model.event.trigger("removeLayer", this.model);
                        this.model.triggered = false;
                        Message_bone.trigger("closeButtonHide");
                    } else {
                        Message_bone.one("loading", this.proxy(function () {
                            var renderData = {
                                buttonStat: this.model.buttonStat,
                                condition: this.model.condition,
                                value: this.model.input

                            };
                            this.render(renderData);
                        }));
                        Message_bone.one("loaded", this.proxy(function () {
                            var renderData = {
                                buttonStat: this.model.buttonStat,
                                condition: this.model.condition,
                                value: this.model.input
                            };
                            this.render(renderData);
                        }));
                        this.model.event.trigger("removeLayer", this.model);
                        this.model.layer = null;
                        var data = {
                            url: this.el.attr("data-baseUrl"),
                            query: this.el.attr("data-query"),
                            queryName: this.el.attr("data-queryname"),
                            layer: this.el.attr("data-layer"),
                            symbol: this.el.attr("data-symbol"),
                            detail: this.el.attr("data-detail"),
                            content: this.el.attr("data-content"),
                            value: this.model.input
                        };
                        this.model.canTrigger = true;
                        this.model.event.trigger("loadLayer", data);
                    }
                },

                model: model,
                parentModel: parentModel
            });
            return new trigger(selector);
        },
        createAllTrigger: function (ddlist, data) {
            var len = ddlist.length, t = 0;
            while(this.subTrigger[i]) {
                this.subTrigger[i].destroy();
                i += 1;
            }
            for (var i = 0; i < len; i++) {
                var contentName = $(ddlist[i]).attr("data-content");
                var condition = data.condition[contentName];
                this.model.event.trigger("create", contentName);
                while(!this.model.find(this.model.childId));
                var ddModel = this.model.find(this.model.childId)[contentName];
                ddModel.condition = condition;
                var buttonStat = ddModel["buttonStat"];
                var renderData = {
                    buttonStat: buttonStat,
                    condition: condition,
                    value: ddModel.input
                };
                this.subTrigger[$(ddlist[i]).data('content')] = this.createTrigger(ddlist[i], ddModel, this.model.find(this.model.childId));
                this.subTrigger[$(ddlist[i]).data('content')].render(renderData);
            }
        },
        mouseScroll: function (dl) {
            //var time;
            //var scrollLength = 0;
            function mousewheel(e) {
                var scroll;
                var that = this;
                var originHeight = this.clientHeight + this.scrollTop;
                var fullHeight = this.scrollHeight;
                if (originHeight < fullHeight) {
                    scroll = e.originalEvent.wheelDelta ?
                        e.originalEvent.wheelDelta > 0 ? -20 : 20
                        : e.originalEvent.detail > 0 ? 20 : -20;
                    this.scrollTop += scroll;
                    //if (!time) {
                    //    time = setTimeout(function () {
                    //        if (scrollLength > (fullHeight - originHeight)) scrollLength = fullHeight - originHeight;
                    //        originHeight = that.clientHeight + that.scrollTop + scrollLength;
                    //        originHeight >= fullHeight ? $(that.parentNode).find("div.css-page").removeClass("css-pageScroll")
                    //            : $(that.parentNode).find("div.css-page").addClass("css-pageScroll");
                    //        $(that).animate({
                    //            scrollTop: that.scrollTop + scrollLength
                    //        }, 800, function() {
                    //            scrollLength = 0;
                    //            time = null;
                    //        });
                    //    }, 10);
                    //}
                    originHeight = this.clientHeight + this.scrollTop;
                    originHeight >= fullHeight ? $(that.parentNode).find("div.css-page").removeClass("css-pageScroll")
                                : $(that.parentNode).find("div.css-page").addClass("css-pageScroll");
                } else {
                    scroll = e.originalEvent.wheelDelta ? e.originalEvent.wheelDelta > 0 && 20
                        : e.originalEvent.detail < 0 && 20;
                    this.scrollTop -= scroll;
                }
            }
            $(dl).on("DOMMouseScroll", mousewheel);
            $(dl).on("mousewheel", mousewheel)
        },
        model: handle.PagesData
    });
    var triggerClick = new toggleClass("#popup .js-popup");
    var ddlist = triggerClick.el.find(".css-slicepage dl dd");
    //triggerClick.createAllTrigger(ddlist);
    return {
        slicePageController: triggerClick
    }
});